<?php
/**
 * 编辑员工信息
 *
 * @author Dracowyn
 * @since 2023-11-17 14:24
 */

// 引入配置文件
include_once('config/config.php');

$loginAuth = check_auth();

$id = $_GET['id'] ?? 0;
$personSql = "SELECT `p`.*,`pr`.`name` AS `prname`,`c`.`name` AS `cname`,`dis`.`name` AS `disname` FROM `pre_person` AS `p` LEFT JOIN `pre_region` AS `pr` ON `p`.`province` = `pr`.`code` LEFT JOIN `pre_region` AS `c` ON `p`.`city` = `c`.`code` LEFT JOIN `pre_region` AS `dis` ON `p`.`district` = `dis`.`code` WHERE `id` = '$id'";
$personData = find($personSql);

if (!$personData) {
	showMsg('员工不存在');
	exit();
}

$depSql = "SELECT * FROM pre_department";

$depData = all($depSql);

$depId = $personData['depid'] ?? 0;

$jobSql = "SELECT * FROM pre_job WHERE depid = $depId";

$jobData = all($jobSql);

if ($_POST) {
	$name = trim($_POST['name']);
	$mobile = trim($_POST['mobile']);
	$email = trim($_POST['email']);
	$address = trim($_POST['address']);
	$code = trim($_POST['code'] ?? '');
	$personData = "SELECT * FROM pre_person WHERE id != $id";
	$personData = all($personData);
	foreach ($personData as $key => $value) {
		if ($mobile == $value['mobile']) {
			showMsg('手机号已存在');
			exit();
		}
		if ($email == $value['email']) {
			showMsg('邮箱已存在');
			exit();
		}
	}

	$data = [
		'name' => $name,
		'mobile' => $mobile,
		'email' => $email,
		'gender' => $_POST['gender'],
		'depid' => $_POST['depId'],
		'jobid' => $_POST['jobId'],
		'address' => $address,
	];

	$regionSql = "SELECT * FROM pre_region WHERE code = $code";
	$parentPath = find($regionSql);
	if (!$parentPath) {
		showMsg('请选择正确的地区');
	}
	[$province, $city, $district] = explode(',', $parentPath['parentpath']);

	$data['province'] = $province ?? null;
	$data['city'] = $city ?? null;
	$data['district'] = $district ?? null;

	if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
		$res = upload('avatar');
		if ($res['code'] === 0) {
			showMsg($res['msg']);
		}
		$data['avatar'] = $res['data']['filename'];
	}

	$result = update('person', $data, "id = $id");

	if ($result['code'] === 0) {
		@is_file('./upload/' . $data['avatar']) && @unlink('./upload/' . $data['avatar']);
		showMsg($result['msg']);
		exit();
	} else {
		if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
			@is_file('./upload/' . $personData['avatar']) && @unlink('./upload/' . $personData['avatar']);
		}
		showMsg('更新成功', 'personList.php');
	}
}

?>

<!DOCTYPE html>
<html lang="zh">

<head>
	<?php include_once('common/meta.php'); ?>
    <link rel="stylesheet" href="assets/city-picker/city-picker.css">
    <title>编辑员工信息</title>
</head>

<style>
    #upload {
        width: 200px;
        height: 200px;
        cursor: pointer;
    }
</style>

<body>
<?php include_once('common/header.php'); ?>
<?php include_once('common/menu.php'); ?>
<div class="content">
    <div class="header">
        <h1 class="page-title">编辑员工</h1>
    </div>
    <ul class="breadcrumb">
        <li><a href="index.php">首页</a> <span class="divider">/</span></li>
        <li><a href="personList.php">员工管理</a> <span class="divider">/</span></li>
        <li class="active">编辑员工</li>
    </ul>

    <div class="container-fluid">
        <div class="row-fluid">

            <div class="btn-toolbar">
                <button class="btn btn-primary" onClick="location='personList.php'"><i class="icon-list"></i> 员工列表
                </button>
                <div class="btn-group">
                </div>
            </div>

            <div class="well">
                <div id="myTabContent" class="tab-content">
                    <div class="tab-pane active in" id="home">
                        <form method="post" enctype="multipart/form-data">

                            <label for="name">姓名</label>
                            <input type="text" name="name" id="name" placeholder="请输入姓名" required
                                   class="input-xxlarge"
                                   value="<?php echo $personData['name']; ?>">

                            <label for="mobile">手机号</label>
                            <input type="text" name="mobile" id="mobile" placeholder="请输入手机号" required
                                   class="input-xxlarge"
                                   value="<?php echo $personData['mobile']; ?>">

                            <label for="email">邮箱</label>
                            <input type="email" name="email" id="email" placeholder="请输入邮箱" required
                                   class="input-xxlarge"
                                   value="<?php echo $personData['email']; ?>">

                            <label>性别</label>
                            <label>
                                <select name="gender" class="input-xlarge">
                                    <option value="0" <?php echo $personData['gender'] == 0 ? 'selected' : '' ?>>保密
                                    </option>
                                    <option value="1" <?php echo $personData['gender'] == 1 ? 'selected' : '' ?>>男
                                    </option>
                                    <option value="2" <?php echo $personData['gender'] == 2 ? 'selected' : '' ?>>女
                                    </option>
                                </select>
                            </label>

                            <label for="depId">部门</label>
                            <select name="depId" id="depId" class="input-xlarge">
                                <option value="0">请选择</option>
								<?php foreach ($depData as $item) { ?>
                                    <option value="<?php echo $item['id']; ?>" <?php echo $personData['depid'] == $item['id'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>

								<?php } ?>
                            </select>

                            <label for="jobId">职位</label>
                            <select name="jobId" id="jobId" class="input-xlarge">
                                <option value="0">请选择</option>
								<?php foreach ($jobData as $item) { ?>
                                    <option value="<?php echo $item['id']; ?>" <?php echo $personData['jobid'] == $item['id'] ? 'selected' : '' ?>><?php echo $item['name']; ?></option>

								<?php } ?>
                            </select>

                            <label for="region">选择地区</label>
                            <div style="position: relative;height:30px;margin-bottom: 10px;">
                                <input type="text" name="region" id="region" placeholder="请选择地区" required
                                       class="input-xxlarge" readonly data-toggle="city-picker">
                                <input type="hidden" name="code" id="code"
                                       value="<?php echo $personData['district'] ?: ($personData['city'] ?: $personData['province']) ?>">
                            </div>

                            <label for="address">详细地址</label>
                            <input type="text" name="address" id="address" placeholder="请输入详细地址" required
                                   class="input-xxlarge" value="<?php echo $personData['address']; ?>">

                            <label>头像</label>
                            <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                            <img src="<?php echo is_file('./upload/' . $personData['avatar']) ? '/upload/' . $personData['avatar'] : 'assets/images/upload.png' ?>"
                                 id="upload" onclick="avatar.click();" alt="">
                            <label></label>
                            <input class="btn btn-primary" type="submit" value="提交"/>
                        </form>
                    </div>
                </div>
            </div>

			<?php include_once('common/footer.php'); ?>

        </div>
    </div>
</div>
</body>

<?php include_once 'common/script.php'; ?>
<script src="assets/city-picker/city-picker.data.min.js"></script>
<script src="assets/city-picker/city-picker.min.js"></script>
<script>
    $('#avatar').change(function () {
        let file = $(this)[0].files[0];
        if (file) {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                $('#upload').attr('src', reader.result);
            }
        }
    })

    $('#region').citypicker('reset').citypicker('destroy').citypicker({
        province: `<?php echo $personData['prname'];?>`,
        city: `<?php echo $personData['cname'];?>`,
        district: `<?php echo $personData['disname']; ?>`,
    }).on('cp:updated', function () {
        let citypicker = $(this).data("citypicker");
        let code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
        $('#code').val(code);
    });

    // 查询职位
    $('#depId').change(function () {
        let depId = $('#depId').val();
        $.ajax({
            type: 'post',
            url: 'ajax.php',
            data: {
                depId,
                action: 'job',
                adminId: `<?php echo $loginAuth['id']; ?>`
            },
            dataType: 'json',
            success: function (res) {
                if (res) {
                    if (res.code === 1) {
                        let option = '';
                        for (let item of res.data) {
                            option += `<option value="${item.id}">${item.name}</option>`
                        }
                        $('#jobId').html(option);
                    } else {
                        $('#jobId').html(`<option value="0">请选择</option>`)
                    }
                }
            }
        })
    });
</script>

</html>

